const {
  Admin,
  User,
  Message
} = require("../model/dbmodel")
const bcrypt = require("./bcrypt")

const os = require('os');
const admin = require("../router/admin");
function getLocalIP() {
  const interfaces = os.networkInterfaces();
  const addresses = [];
  for (const interfaceName in interfaces) {
    const interfaceObj = interfaces[interfaceName];
    for (const address of interfaceObj) {
      if (address.family === 'IPv4' && !address.internal) {
        addresses.push(address.address);
      }
    }
  }
  return addresses[0] || 'localhost';
}
let localhost = "http://" + getLocalIP() + ":5431";
// 添加消息
exports.isAdmin = (data, res) => {
  console.log(data, "isAdmin data");
  res.send({ status: 200, message: "管理员", authority: 1 })
}
exports.addAdmin = (data, res) => {
  //查询邮箱 用户表是否存在
  let wherestr = { email: data.email }
  let adminDate = {
    userID: '',
    email: data.email,
    authority: 1,
    time: new Date()
  }
  Admin.exists({ email: data.email }).then(result => {
    if (result) {
      console.log(result, "result");
      res.send({ status: 300, message: "用户是管理员！" })
    } else {
      User.findOne(wherestr).then(result => {
        if (result) {
          adminDate.userID = result._id
          let AdminUser = new Admin(adminDate)
          AdminUser.save((err, data) => {
            if (err) {
              res.send({ status: 500, message: "系统繁忙！" })
            } else {
              res.send({ status: 200, message: "新增成功！" })
            }

          })
        } else {
          res.send({ status: 200, message: "用户不存在！" })
        }
      })
    }
  })

}
// 查询管理员 根据admin中的userid 去user表中查找用户数据 最终返回匹配的数据
exports.getAdminList = (data, res) => {
  // 执行查询 
  // res.send({ status: 200,   message: "查询成功" })
  // return;
  Admin.find()
    .populate({
      path: 'userID',
      // 使用 $lookup 进行联表查询
      match: { email: { $exists: true } },
      // 使用 $project 对结果进行过滤
      project: { _id: 0, name: 1 },
      model: 'User'
    })
    .then(admins => {
      // console.log(admins,"admins");
      let adminlist = admins.map(item => item.userID).map(item => {
        item.imgrul = localhost + item.imgrul
        return item;
      })
      // console.log(adminlist, "adminlist");
      res.send({ status: 200, data: adminlist, message: "查询成功" })
    })
    .catch(error => {
      console.log(error, "error");
      res.send({ status: 500, message: "系统繁忙！" })
    });

}
exports.deleteAdmin = (data, res) => {
  console.log(data, "data");
  Admin.deleteMany({ email: data.email })
    .then(result => {
      console.log(result.deletedCount, "del count");
      res.send({ status: 200, message: "删除成功！" })
    })
    .catch(error => {
      res.send({ status: 500, message: "系统繁忙！" })

    });
}

exports.register = (data, res) => {
  console.log(data, "register data");
  let item = {
    email: "admin",
    password: "password",
    authority: 1,
    time: new Date()
  }
  res.send({ status: 200, message: "注册接口已经关闭，请联系管理员2830904279@qq.com" })
  return;
  let admin = new Admin(item)
  admin.save((result, err) => {
    if (err) {
      // 修改失败
      console.log(err, "修改失败");
      res.send({ status: 500 });
    } else {
      console.log(result, "新增成功");
      res.send({ status: 200 });
    }
  })
}

function getAdminInfoAsync(model, wherestr = {}) {
  return new Promise((resolve, reject) => {
    model.countDocuments(wherestr, (err, count) => {
      if (err)
        reject(err)
      else
        resolve(count)
    })
  })
}
exports.getAdminInfo = async (data, res) => {
  let info = {
    userCount: 0,
    adminCount: 0,
    messageCount: 0,
    registerRecent: 0
  }
  try {
    info.userCount = await getAdminInfoAsync(User, {})
    info.adminCount = await getAdminInfoAsync(Admin, {})
    info.messageCount = await getAdminInfoAsync(Message, {})
    const sevenDaysAgo = new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000);
    info.registerRecent = await getAdminInfoAsync(User, { time: { $gte: sevenDaysAgo } })
    res.send({ status: 200, info, message: "获取成功" })
  } catch (err) {
    res.send({ status: 500, message: "服务器错误" })

  }
}

//首页展示数据
const now = new Date();
const pipeline = [
  {
    $match: { time: { $gte: new Date(now.getFullYear() - 1, now.getMonth(), now.getDate()) } }
  },
  {
    $group: {
      _id: { year: { $year: "$time" }, month: { $month: "$time" } },
      count: { $sum: 1 }
    }
  },
  {
    $project: {
      year: "$_id.year",
      month: "$_id.month",
      count: 1,
      新增用户数: { $sum: "$count" }
    }
  },
  {
    $group: {
      _id: { year: "$year", month: "$month" },
      count: { $sum: "$新增用户数" }
    }
  },
  {
    $project: {
      _id: 0,
      year: "$_id.year",
      month: "$_id.month",
      count: 1
    }
  },
  {
    $sort: { year: 1, month: 1, count: -1 }
  }
];
function getChartDateByPip(model) {
  return new Promise((resolve, reject) => {
    model.aggregate(pipeline, (error, result) => {
      if (error) {
        reject('聚合错误:', error);
        return;
      }
      // 打印每个月的新增用户数
      resolve(result);

    });
  })
}
exports.getChartDate = async (data, res) => {
  try {
    let userChartData = await getChartDateByPip(User)
    let messageChartData = await getChartDateByPip(Message)
    res.send({ status: 200, data: { userChartData, messageChartData }, message: "获取成功" })
  } catch (err) {
    res.send({ status: 500, message: err })
  }
}


//分页函数
async function paginateUsers(page = 1, pageSize = 10) {
  // 获取跳过的记录数
  const skip = (page - 1) * pageSize;

  // 使用 skip() 和 limit() 方法进行分页查询
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(1)
    }, Math.random() * 1000)
  })
  const users = await User.find().skip(skip).limit(pageSize);

  return users;
}



exports.getPageUsers = async ({ page, pageSize }, res) => {
  try {
    const pageUsers = await paginateUsers(page, pageSize);
    pageUsers.forEach(user => {
      user.imgrul = localhost + user.imgrul;
    })
    res.send({ status: 200, data: pageUsers, message: "获取成功" })
  } catch (err) {
    res.send({ status: 500, message: err })
  }
}

//删除用户
exports.deleteUser = (data, res) => {
  console.log(data);
  User.findByIdAndRemove(data.id, (err, user) => {
    if (err) {
      res.send({ status: 500, message: "系统繁忙！" })
      return;
    }
    if (!user) {
      console.error('未找到要删除的文档');
      return;
    }
    res.send({ status: 200, message: "删除成功" })
  })
}
exports.updateUserDetail = (data, res) => {
  //这里修改密码没有写加密
  if (data.psw == "") delete data.psw
  else {
    data.psw = bcrypt.encryption(data.psw)
  }
  delete data.imgrul
  console.log(data, "data");
  User.findByIdAndUpdate(data._id, data, (err, result) => {
    if (err) {
      res.send({ status: 500, message: "系统繁忙！" })
    } else {
      res.send({ status: 200, message: "修改成功" })
    }
  });
}